const UserModel = require('../../modules/admin/user');
const toPwd = require('../../utils/utils').toPwd;

class userController {
  /**
   * 添加用户
   * @param ctx
   * @returns {Promise.<void>}
   */
  static async create(ctx) {
    // 接收客服端
    let req = ctx.request.body;
    if (req.username // 用户名
      && req.password // 密码
    ) {
      try {
        // 创建用户模型
        const ret = await UserModel.createUser(req);

        ctx.response.status = 200;
        ctx.body = {
          code: 200,
          msg: '添加用户成功'
        }

      } catch (err) {
        ctx.response.status = 412;
        ctx.body = {
          code: 200,
          msg: '添加用户失败',
          data: err
        }
      }
    } else {
      ctx.response.status = 416;
      ctx.body = {
        code: 2001,
        msg: '参数不齐全',
      }
    }

  }

  /**
   * 用户登陆
   * @param ctx
   * @returns {Promise.<void>}
   */
  static async adminLogin(ctx) {
    let username = ctx.request.body.username;
    let password = ctx.request.body.password;

    ctx.response.status = 200;

    if (username && password) {
      try {
        // 验证密码
        let pwd = toPwd(password);
        let data = await UserModel.adminLogin(username, pwd);

        // console.log(data);

        if(data){

          // 验证成功后写入session
          ctx.session.username = username;
          ctx.session.userID = data.dataValues.id;

          ctx.body = {
            code: 0,
            msg: '登陆成功'
          }

        }else{
          ctx.body = {
            code: 2004,
            msg: '用户名或密码不正确'
          }
        }

        

      } catch (err) {
        ctx.body = {
          code: -1,
          msg: err
        }
      }
    } else {
      ctx.body = {
        code: 2004,
        msg: '用户名或密码不正确'
      }
    }
  }



  /**
   * 修改密码
   * @param ctx
   * @returns {Promise.<void>}
   */
  static async editPwd(ctx) {
    let id = ctx.request.body.id;

    // 以下是新密码
    let password = ctx.request.body.password;
    let repassword = ctx.request.body.repassword;

    ctx.response.status = 200;

    if(!id){
      ctx.body = {
        code: 2001,
        msg: "缺少参数 'ID'"
      }
      return;
    }


    if(!password){
      ctx.body = {
        code: 2001,
        msg: "缺少参数 'password'"
      }
      return;
    }

    if(!repassword){
      ctx.body = {
        code: 2001,
        msg: "缺少参数 'repassword'"
      }
      return;
    }

    try {

      if(password !== repassword){

        ctx.body = {
          code: 2003,
          msg: '两次密码不一致'
        }
        return;
      }

      let res = await UserModel.editPwd(id,{
        password: toPwd(password)
      });

      console.log(res);
      if(res[0] == 1){
        ctx.body = {
          code: 0,
          msg: '修改成功'
        }
      }else{
        ctx.body = {
          code: 0,
          msg: 'ID不存在'
        }
      }

    } catch (err) {
      ctx.body = {
        code: -1,
        msg: err
      }
    }
  }


}

module.exports = userController